import { BaseEvent } from "./baseEvent"
import Editor from "../editor"
import { debounce } from "utils"

export class ViewEvent extends BaseEvent {
  // @ts-ignore
  private container: HTMLElement
  constructor(private editor: Editor, container: HTMLElement) {
    super()
    this.editor = editor
    this.container = container
  }

  private selectionChangeHandler = () => {
    const domSelection = window.getSelection()

    if (domSelection) {
      const anchor = domSelection.anchorOffset
      const focus = domSelection.focusOffset
      if (
        anchor === this.editor.getSelectionModel().selection.anchor &&
        focus === this.editor.getSelectionModel().selection.focus
      )
        return
      // 交给 KeyboardEvent的事件监听处理
      this.editor.emit("selection-change", {
        anchor,
        focus,
      })
    }
  }

  private doubleClickHandler = () => {
    const domSelection = window.getSelection()
    if (domSelection) {
      // 交给 事件监听处理
      this.editor.emit("selection-change", {
        anchor: domSelection.anchorOffset,
        focus: domSelection.focusOffset,
      })
    }
  }

  addListeners = () => {
    window.document.addEventListener(
      "selectionchange",
      debounce(this.selectionChangeHandler, 50),
    )
    this.container.addEventListener("dblclick", this.doubleClickHandler)
  }

  removeListeners = () => {
    window.document.removeEventListener(
      "selectionchange",
      this.selectionChangeHandler,
    )
    this.container.removeEventListener("dblclick", this.doubleClickHandler)
  }
}
export default ViewEvent
